package top.jingles.sayhiintime;

import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.os.Environment;

import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.util.Calendar;

public class CheckTimeListener
        extends AsyncTask<Void, Void, Void> {
    private static MediaPlayer mPlayer;
    private boolean isStoped = true;

    public static void ResReset() {
        try {
            if (mPlayer != null) {
                if (mPlayer.isPlaying()) {
                    mPlayer.stop();
                }
                mPlayer.release();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public static boolean previewClock(int hourNum) {
        return previewClock(hourNum, true);
    }

    public static boolean previewClock(int hourNum, boolean showNotify) {
        for (int i = 0; i < 3; i++) {

            String voicePath = new StringBuilder(String.valueOf(Environment.getExternalStorageDirectory().getPath()))
                    .append(Setting.getInstance().getSoundPath())
                    .append(Setting.getInstance().getVoiceStyleName())
                    .append("/").toString() + String.valueOf(hourNum);
            String voiceFilename = voicePath + new String[]{".wav", ".mp3", ".ogg"}[i];


            if (!new File(voiceFilename).exists()) {
                continue;
            }
            try {
                System.out.println(voiceFilename);
                mPlayer = new MediaPlayer();
                mPlayer.reset();
                if (!mPlayer.isPlaying()) {
                    System.out.println("Media Player is not playing now");
                    mPlayer.setDataSource(voiceFilename);
                    mPlayer.prepare();
                    mPlayer.start();

                    if (showNotify) {
                        CheckTimeService.getInstance().showNotify("燕姿说：", Setting.getSaywords(hourNum));
                    }
                    return true;
                } else {
                    System.out.println("Media Player is playing, stop execute");
                }
            } catch (IllegalStateException ex1) {
                System.out.println("ERROR happened 1");
                ex1.printStackTrace();
            } catch (IOException ex2) {
                System.out.println("ERROR happened 2");
            }

        }
        return false;
    }

    private void sleep(int second) {
        try {
            System.out.println(second + "s heart beat");
            Thread.sleep(second * 1000L);
        } catch (InterruptedException ex) {
            ex.printStackTrace();
        }
    }

    private void startListener() {
        int lastHour = -1;
        this.isStoped = false;
        while (true) {
            if (this.isStoped) {
                break;
            }
            Calendar localCalendar = Calendar.getInstance();
            int hour = localCalendar.get(Calendar.HOUR_OF_DAY);
            int minute = localCalendar.get(Calendar.MINUTE);
            int second = localCalendar.get(Calendar.SECOND);
            int sleepSec = 10;
            if (minute == 59 && second >= 50)
                sleepSec = 1;
            if ((minute == 0) && (second < 3) && (lastHour != hour)) {
                CheckTimeService.getInstance().showNotify("燕姿说：", Setting.getSaywords(hour));
                trySpeak(hour);
                lastHour = hour;
            }
            sleep(sleepSec);
        }
    }

    public static void trySpeak(int hour) {
        trySpeak(hour, true);
    }

    public static void trySpeak(int hour, boolean showNotify) {
        String str = Setting.getWords(hour);
        if ((str == null) || (str.length() == 0)) {
            previewClock(hour, showNotify);
            return;
        }
        if (showNotify) {
            CheckTimeService.getInstance().showNotify("燕姿说：", str);
        }
        TTSEngine ttsEngine = TTSEngine.getInstance();
        ttsEngine.SetTTSPath(Environment.getExternalStorageDirectory().getPath() + Setting.getInstance().getTtsPath());
        ttsEngine.SetContent(str);
        ttsEngine.SetRole(4);
        ttsEngine.Start();
    }

    protected Void doInBackground(Void... args) {
        startListener();
        return null;
    }

    public boolean isStoped() {
        return this.isStoped;
    }

    public void setStoped(boolean stoped) {
        this.isStoped = stoped;
    }
}
